<?php
require_once("lib/redbeanwrapper.php");
require_once("models/author.php");

class Item extends RedBeanModel
{
	/**
	 * Returns an array of Items containing all items a certain user with 
	 * username $username has not read. 
	 */
	static public function getUnreadItemsForUsername($username)
	{
		$ids = RBDB::databaseAdapter()->getCol("
			SELECT item.id 
			FROM 
			   item LEFT JOIN feed_item 
			   ON item.id = feed_item.id 
			WHERE 
			   item.read = false 
			ORDER BY item.date ASC
			  "
			  /* AND feed_item.feed 
			   IN 
			      (SELECT feed 
			      FROM @feed_user
			      WHERE user = " . $db->escape($username) . ")"); */
		  );

		$beans =  RBDB::redbean()->batch("Item", $ids);
		return $beans;
	}

	/**
	 * Takes a SimplePie item and writes all relevant data to the 
	 * database. Returns the resulting object. 
	 */
	static function add($item)
	{
		$obj = new Item();
		$obj->itemid = $item->get_id();
		$obj->title = $item->get_title();
		$obj->url = $item->get_permalink();
		$obj->date = $item->get_date("U");
		$obj->content = $item->get_content();
		$obj->read = false;

		$obj->save();

		// The item in in the db, now associate it with its authors
		$authors = Author::addAuthors($item->get_authors());
		foreach($authors as $author)
			$obj->associate($author);
		
		return $obj;
	}

	/**
	 * Returns the Author objects this Item was written by.
	 */
	public function getAuthors()
	{
		return RBDB::redbean()->batch("Author", parent::related("author"));
	}

	/**
	 * Returns true if there is an Item with that id and false if there 
	 * isn't. 
	 */
	static function exists($id)
	{
		$r = Finder::where("item", " itemid = :id", array(":id" => $id));
		if(count($r) > 0)
			return true;
		else
			return false;
	}
}

?>
